package org.codehaus.activemq.transport.composite;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import javax.jms.JMSException;
import org.codehaus.activemq.message.WireFormat;
import org.codehaus.activemq.transport.TransportChannel;
import org.codehaus.activemq.transport.TransportChannelFactory;
import org.codehaus.activemq.util.JMSExceptionHelper;

public class CompositeTransportChannelFactory
  implements TransportChannelFactory
{
  private String separator = ",";

  public TransportChannel create(WireFormat wireFormat, URI remoteLocation) throws JMSException {
    try {
      return new CompositeTransportChannel(wireFormat, parseURIs(remoteLocation));
    } catch (URISyntaxException e) {
    	  throw JMSExceptionHelper.newJMSException("Can't parse list of URIs for: " + remoteLocation + ". Reason: " + e, e);
    	  
    }
   }

  public TransportChannel create(WireFormat wireFormat, URI remoteLocation, URI localLocation) throws JMSException
  {
    return create(wireFormat, remoteLocation);
  }

  public boolean requiresEmbeddedBroker() {
    return false;
  }

  protected URI[] parseURIs(URI uri) throws URISyntaxException {
    String text = uri.getSchemeSpecificPart();
    List uris = new ArrayList();
    StringTokenizer iter = new StringTokenizer(text, this.separator);
    while (iter.hasMoreTokens()) {
      uris.add(new URI(iter.nextToken().trim()));
    }
    URI[] answer = new URI[uris.size()];
    uris.toArray(answer);
    return randomizeURIs(answer);
  }

  protected URI[] randomizeURIs(URI[] uris)
  {
    return uris;
  }
}